<style lang="less">
  #div_truck_load_manage {
    p {
      margin-top: 0px;
      margin-bottom: 0px;
    }
    .active_no {
      color: #ff8420;
    }
    .active_yes {
      color: red;
    }
    .el-table .warning-row {
      background: #FFAEB9;
    }
  }
</style>
<template>
  <div id="div_truck_load_manage">
    <el-row class="f-mt f-wa f-mb10">
      <el-col :span="24" class="f-mb10">
        <div>
          <el-tabs v-model="tloStatus" type="border-card" @tab-click="tabClick">
            <el-tab-pane v-for="(op,index) in statusList" :label="op.statusName + '  ' + op.orderQuantity"
                         :name="op.status.toString()" :key="index">
              <el-col :span="24">
                <ue-search-bar ref="ueSearchBar"
                               v-if="['101015000','101015099'].contains(tloStatus)"
                               v-model="searchForm" :data="truckLoadOrderAlls" label-width="120px">
                </ue-search-bar>
                <ue-search-bar ref="ueSearchBar" v-if="['101015001','101015002'].contains(tloStatus)"
                               v-model="searchForm" :data="truckLoadOrderAccepts" label-width="120px">
                </ue-search-bar>
                <ue-search-bar ref="ueSearchBar"
                               v-if="['101015003','101015004','101015005','101015006','101015007'].contains(tloStatus)"
                               v-model="searchForm" :data="truckLoadOrderVehicleDispatchingLaters"
                               label-width="120px">
                </ue-search-bar>
              </el-col>
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-col>
      <el-col :span="24">
        <el-button type="primary" class="f-wa f-fr f-ml10 f-mr20" @click="resetSearchForm">重置</el-button>
        <el-button type="primary" class="f-wa f-fr f-ml10" @click="findTruckLoadManagesByFilters">查询</el-button>
      </el-col>
    </el-row>
    <el-table :data="truckLoadOrders" border style="width: 100%"
              :row-class-name="tableRowClassName">
      <el-table-column :key="Math.random()" prop="truckLoadNumber" label="订单编号" width="150">
        <template slot-scope="scope">
          <p style="color: #409eff" @click="selectTruckLoadDialogClick(scope.row,true)">
            {{scope.row.truckLoadNumber}}
          </p>
          <p>
            <label style="color: red">{{scope.row.createTypeName}}</label>
            <label style="background-color:#409eff">{{scope.row.statusName}}</label>
          </p>
          <p v-for="(item,index) in scope.row.timeoutRemindText" :key="index">
            <label>
              <i class="fa fa-exclamation-circle" aria-hidden="true"
                 v-bind:class="{ active_no: item.indexOf('即将')!=-1, active_yes:item.indexOf('已经')!=-1}"></i>
              {{item}}
            </label>
          </p>
        </template>
      </el-table-column>
      <el-table-column :key="Math.random()" prop="mebPersonalName" label="客户信息" width="120">
        <template slot-scope="scope">
          <p>
            <label>{{scope.row.mebPersonalName}}</label>
          </p>
          <p>
            <label v-if="scope.row.personalLevel!==107005001"
                   style="color: #ff8420">{{scope.row.personalLevelName}}</label>
          </p>
          <p>{{scope.row.memberPhone}}</p>
        </template>
      </el-table-column>
      <el-table-column :key="Math.random()" label="接单领头羊" width="100">
        <template slot-scope="scope">
          <p>{{scope.row.truckBellwetherRealName}}</p>
          <p>{{scope.row.truckBellwetherPhone}}</p>
        </template>
      </el-table-column>
      <el-table-column :key="Math.random()" label="订单时间" width="180">
        <template slot-scope="scope">
          <p>客户下单</p>
          <p>{{scope.row.createdDate}}</p>
          <p>预计发车</p>
          <p>{{scope.row.predictDepartCarDate.substring(0, 16)}} </p>
        </template>
      </el-table-column>
      <el-table-column :key="Math.random()" prop="carInfo" label="车辆信息" width="120">
        <template slot-scope="scope">
          <p>{{scope.row.trucksTypeName}} | {{scope.row.trucksLengthName}}米</p>
          <p>{{scope.row.weight}}吨 | {{scope.row.volume}}方</p>
        </template>
      </el-table-column>
      <el-table-column :key="Math.random()" prop="orderAmount" label="运费（元）" width="120">
        <template slot-scope="scope">
          <p>发布运价：<label style="color: red">{{scope.row.discountPrice}}</label></p>
          <p>货主议价：<label style="color: red">{{scope.row.bargainPrice}}</label></p>
          <p>商定运费：<label style="color: red">{{scope.row.negotiatePrice}}</label></p>
          <p>付款方式：<label style="color: #409eff">{{scope.row.paymentTypeName}}</label></p>
        </template>
      </el-table-column>
      <el-table-column :key="Math.random()" label="指派司机" width="150"
                       v-if="!['101015001', '101015002'].contains(tloStatus)">
        <template slot-scope="scope">
          <div v-if="scope.row.driverPhone!=null">
            <p>{{scope.row.driverName}} | {{scope.row.driverPhone}}</p>
            <p>{{scope.row.plateNumber}}</p>
            <p>消息费:{{scope.row.infoPrice}}</p>
            <p style="color: red">{{scope.row.payStatusName}}</p>
          </div>
          <div v-else>
            -
          </div>
        </template>
      </el-table-column>
      <el-table-column :key="Math.random()" prop="discount" label="货物信息" width="100">
        <template slot-scope="scope">
          <p>{{scope.row.cargoTypeName}}|{{scope.row.cargoName}}</p>
          <p>{{scope.row.weight}}吨|{{scope.row.volume}}方</p>
          <p>{{scope.row.assembleTypeName}}</p>
        </template>
      </el-table-column>
      <el-table-column :key="Math.random()" prop="discountPrice" label="发货人信息">
        <template slot-scope="scope">
          <p>{{scope.row.startContactName}}</p>
          <p>{{scope.row.startContactPhone}}</p>
          <p>{{scope.row.startContactAddressNames + scope.row.startContactStreet}}</p>
        </template>
      </el-table-column>
      <el-table-column :key="Math.random()" label="收货人信息">
        <template slot-scope="scope">
          <p>{{scope.row.endContactName}}</p>
          <p>{{scope.row.endContactPhone}}</p>
          <p>{{scope.row.endContactAddressNames + scope.row.endContactStreet}}</p>
        </template>
      </el-table-column>
      <el-table-column :key="Math.random()" prop="cause" label="关闭原因"
                       v-if="tloStatus==='101015007'">
        <template slot-scope="scope">
          <p>关闭类型：
            {{scope.row.closedTypeName}}
          </p>
          <p>{{scope.row.closedOrderDescription}}</p>
        </template>
      </el-table-column>
      <el-table-column :key="Math.random()" prop="cause" label="异常反馈" width="70"
                       v-if="!['101015001', '101015002'].contains(tloStatus)">
        <template slot-scope="scope">
          <p style="color: #409eff" v-if="scope.row.exceptionNum !== 0"
             @click="selectTruckLoadAbnormalLogsClick(scope.row)">
            {{scope.row.exceptionNum}}
          </p>
          <p v-else>-</p>
        </template>
      </el-table-column>
      <el-table-column :key="Math.random()" prop="compile" label="编辑" width="100px"
                       v-if="!['101015001', '101015002'].contains(tloStatus)">
        <template slot-scope="scope">
          <el-button type="primary" class="f-mt5" v-if="![101015007,101015006].contains(scope.row.status)"
                     @click="truckLoadAbnormalLogClick(scope.row)">异常登记
          </el-button>
          <el-button type="primary" class="f-mt5"
                     v-if="scope.row.status===101015007 && scope.row.isRefundInfoFee===111002001 && scope.row.payStatus === 101003002"
                     @click="refundConfirmationClick(scope.row)">退款确认
          </el-button>
          <el-button type="primary" class="f-mt5"
                     v-if="scope.row.isExceptionSuspended===111002001"
                     @click="exceptionRevert(scope.row)">异常恢复
          </el-button>
          <el-button class="f-mt5" type="primary"
                     v-if="tloStatus==='101015099'&&scope.row.status!==101015007"
                     @click="closeTruckLoadOrderClick(scope.row)">
            关闭订单
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :current-page="currentPage"
      :page-size="pageSize"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      layout="total,sizes,prev,pager,next,jumper"
      :total="total" style="float: right">
    </el-pagination>
    <div>
      <truck-load-order-select-dialog
        :truckLoadModel="truckLoadModel"></truck-load-order-select-dialog>
      <truck-load-abnormal-log-create-dialog
        :truckLoadOrder="truckLoadOrder" v-on:isRefresh="isRefreshFun"></truck-load-abnormal-log-create-dialog>
      <truck-load-abnormal-logs-dialog
        :selectAbnormalLogsBytruckLoadOrderId="selectAbnormalLogsBytruckLoadOrderId"></truck-load-abnormal-logs-dialog>
      <truck-load-order-close-dialog
        :truckLoadOrderCloseModel="truckLoadOrderCloseModel"
        v-on:isRefresh="isRefreshFun"></truck-load-order-close-dialog>
    </div>
  </div>
</template>

<script>
import {
  searchTruckLoadOrders,
  getTruckLoadOrderStatus,
  modifyIsExceptionSuspended,
  refundInfoFee
} from '../../api/truck-load/TruckLoadOrder.js';
import TruckLoadOrderSelectDialog from './TruckLoadOrderSelectDialog.vue';
import TruckLoadAbnormalLogCreateDialog from './TruckLoadAbnormalLogCreateDialog.vue';
import TruckLoadAbnormalLogsDialog from './TruckLoadAbnormalLogsDialog.vue';
import { isEmpty, objToFilter, resetObjNull } from '../../lib/util.js';
import TruckLoadOrderCloseDialog from './TruckLoadOrderCloseDialog.vue';

export default {
  components: {
    TruckLoadOrderCloseDialog,
    TruckLoadOrderSelectDialog,
    TruckLoadAbnormalLogCreateDialog,
    TruckLoadAbnormalLogsDialog
  },
  data () {
    return {
      token: this.$store.state.token,
      isShows: false,
      truckLoadOrder: {},
      truckLoadOrderCloseModel: '',
      selectAbnormalLogsBytruckLoadOrderId: '',
      truckLoadModel: '',
      tloStatus: '101015000',
      statusList: [],
      searchForm: {},
      closeForm: {
        id: null
      },
      driverModel: {},
      truckLoadOrders: [],
      defaultStatus: '101025001',
      currentPage: 1,
      pageSize: 10,
      total: 0
    };
  },
  methods: {
    tableRowClassName ({row, rowIndex}) {
      if (row.exceptionNum > 0) {
        return 'warning-row';
      }
    },
    resetSearchForm () {
      let fms = this.$refs.ueSearchBar;
      for (let i in fms) {
        resetObjNull(fms[i].form);
      }
    },
    refundConfirmationClick (row) {
      this.$confirm('请确认是否将司机支付的信息费全额原路退还给司机支付账户, 是否继续?', '提示', {
        title: '退款确认',
        type: 'warning'
      }).then(() => {
        refundInfoFee(103006009, row.id, row.infoPrice).then((res) => {
          if (res.status === 200) {
            this.$message.success('退款成功');
            this.findTruckLoadManagesByFilters();
          } else {
            this.$message.error('退款失败');
          }
        });
      }).catch(() => {
        this.$message.info('已取消操作');
      });
    },
    isRefreshFun (val) {
      if (val) {
        this.findTruckLoadManagesByFilters();
      }
    },
    selectTruckLoadAbnormalLogsClick (row) {
      this.selectAbnormalLogsBytruckLoadOrderId = JSON.stringify(Object.assign(row, {
        'isShow': true,
        'time': new Date().getTime()
      }));
    },
    truckLoadAbnormalLogClick (row) {
      if ([101015007, 101015006].contains(row.status)) {
        return this.$message.error('已完成或已关闭的订单无法异常登记');
      }
      this.truckLoadOrder = JSON.stringify(Object.assign(row, {
        'isShow': true,
        'time': new Date().getTime()
      }));
    },
    selectTruckLoadDialogClick (row, isDisabled) {
      this.truckLoadModel = JSON.stringify(Object.assign(row, {
        'isShow': true,
        'isDisabled': isDisabled,
        'time': Math.random()
      }));
    },
    tabClick () {
      this.resetSearchForm();
      this.findTruckLoadManagesByFilters();
    },
    findTruckLoadManagesByFilters () {
      let ob = Object.assign({}, this.searchForm);
      let filters = '';
      filters = (((isEmpty(this.tloStatus) || this.tloStatus === '101015000') ? '' : ('EQ_status=' + this.tloStatus + ';')) + objToFilter(ob)).replace('EQ_status=101015099', 'EQ_isExceptionSuspended=111002001');
      filters = filters.replace('EQ_exceptionNum=NOT_NULL', 'NOTEQ_exceptionNum=null');
      if (filters.indexOf('EQ_isExceptionSuspended') === -1 && this.tloStatus !== '101015000') {
        filters += ';EQ_isExceptionSuspended=111002002';
      }
      this.searchTruckLoadOrders(filters);
      this.searchDictEntityTruckLoadOrderType();
    },
    searchTruckLoadOrders (filters) {
      console.log(filters);
      searchTruckLoadOrders({
        filters: filters,
        sort: 'createdDate,desc',
        page: this.currentPage - 1,
        size: this.pageSize
      }).then((res) => {
        this.truckLoadOrders = res.data;
        this.total = Number(res.headers['x-total-count']);
      });
    },
    exceptionRevert (row) {
      this.$confirm('异常挂起订单已经协调解决,将订单恢复至正常状态。, 是否继续?', '提示', {
        title: '异常恢复',
        type: 'warning'
      }).then(() => {
        modifyIsExceptionSuspended(row.id, 111002002, '').then((res) => {
          if (res.status === 200) {
            this.$message.success('恢复成功');
            this.findTruckLoadManagesByFilters();
          } else {
            this.$message.error('恢复失败');
          }
        });
      }).catch(() => {
        this.$message.info('已取消操作');
      });
    },
    closeTruckLoadOrderClick (row) {
      this.truckLoadOrderCloseModel = JSON.stringify(Object.assign(row, {
        'isShow': true,
        'time': new Date().getTime()
      }));
    },
    searchDictEntityTruckLoadOrderType () {
      getTruckLoadOrderStatus().then((res) => {
        if (res.status === 200) {
          this.statusList = res.data;
        }
      });
    },
    // 每页几条操作
    handleSizeChange (val) {
      this.pageSize = val;
      this.findTruckLoadManagesByFilters();
    },
    // 第几页操作
    handleCurrentChange (val) {
      this.currentPage = val;
      this.findTruckLoadManagesByFilters();
    }
  },
  mounted () {
    this.$store.commit('initDict');
    this.findTruckLoadManagesByFilters();
    this.searchDictEntityTruckLoadOrderType();
  },
  computed: {
    btns () {
      return this.$store.state.btns[this.$route.path] || [];
    },
    truckLoadOrderAlls () {
      let common = this.$store.state.querys[this.$route.path + '#truck_load_order_common'] || [];
      let all = Object.assign([], this.$store.state.querys[this.$route.path + '#truck_load_order_all'] || []);
      Array.prototype.push.apply(all, common);
      return all;
    },
    truckLoadOrderAccepts () {
      let common = this.$store.state.querys[this.$route.path + '#truck_load_order_common'] || [];
      let accept = Object.assign([], this.$store.state.querys[this.$route.path + '#truck_load_order_accept'] || []);
      Array.prototype.push.apply(accept, common);
      return accept;
    },
    truckLoadOrderVehicleDispatchingLaters () {
      let common = this.$store.state.querys[this.$route.path + '#truck_load_order_common'] || [];
      let vehicleDispatchingLater = Object.assign([], this.$store.state.querys[this.$route.path + '#truck_load_order_vehicle_dispatching_later'] || []);
      Array.prototype.push.apply(vehicleDispatchingLater, common);
      return vehicleDispatchingLater;
    }
  }
};
</script>
